package org.example.seata.common.security.config.auth.handler;

import cn.hutool.core.collection.CollUtil;
import org.springframework.lang.Nullable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author hzq
 * @date 2021/12/6 11:57
 */
@Component
public class AuthHandlerChain {

    private final List<AuthHandler> authHandlers;

    public AuthHandlerChain(@Nullable List<AuthHandler> authHandlers) {
        this.authHandlers = CollUtil.isNotEmpty(authHandlers) ? authHandlers : Collections.emptyList();
    }

    public UserDetails handler(String handlerType, String principal, String credentials, Map<String, String> parameters) {

        for (AuthHandler authHandler : authHandlers) {
            if (handlerType.equals(authHandler.getHandlerType())) {
                return authHandler.handler(principal, credentials, parameters);
            }
        }

        throw new UnsupportedGrantTypeException("Unsupported handler type: " + handlerType);
    }
}
